class User < ActiveRecord::Base
  #
  # Relations
  #

  has_many :ads
  has_many :comments

  has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "30x30>" }

  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable,
         :registerable,
         :recoverable,
         :rememberable,
         :trackable,
         :validatable

  #
  # Validation
  #

  validates :email, :uniqueness => true
  validates :username, :presence => true,
                       :uniqueness => { :case_sensitive => false }

  validates :name, :presence => true,
                   :length => { :minimum => 2 },
                   :format => { :with => /\A[a-zA-Z]+\z/,
                                :message => "Only letters allowed"}

  validates :first_name, :presence => true,
                         :length => { :minimum => 2 },
                         :format => { :with => /\A[a-zA-Z]+\z/,
                                      :message => "Only letters allowed" }

  validates :description, :presence => true,
                          :length => { :minimum => 10 },
                          :format => { :with => /\A[a-zA-Z]+\z/,
                                      :message => "Only letters allowed" }

  validates :sel_number, :allow_blank => true,
                         :numericality => { :only_integer => true }

  validates :city, :allow_blank => true,
                   :length => { :minimum => 2 },
                   :format => { :with => /\A[a-zA-Z]+\z/,
                                :message => "Only letters allowed"}

  validates :phone, :length => { :is => 10 }, :allow_blank => true

  validates :cp, :length => { :is => 5 },
                 :numericality => { :only_integer => true },
                 :allow_blank => true

  #
  # Methods
  #

  def initialize(params=nil)
    if params
      if not params['money']
        params['money'] = 100 # default peaksel sum
      end
      if not params['is_admin']
        params['is_admin'] = false # default admin
      end
    end
    super
  end

  def admin?
    self.is_admin == true
  end

  def credit sum
    self.money += sum
    self.save
  end
  def debit sum
    self.money -= sum
    self.save
  end

  #
  # Two methods to know current user in model
  #

  def self.current
    Thread.current[:user]
  end
  def self.current=(user)
    Thread.current[:user] = user
  end

  def to_s
    self.username
  end
end
